﻿using AutoMapper;
using FarmSmartSleep.Common.Domain.BeginTable;
using FarmSmartSleep.Common.Domain.PM;
using FarmSmartSleep.Common.Dtos;
using FarmSmartSleep.Common.Infrastructure;
using MediatR;

namespace FarmSmartSleep.Organ.API.Application.ProductionManagement.FemaleRen
{
    public class FemaleRenCreateHandler : IRequestHandler<FemaleRenCreateCommand, Result>
    {
        private readonly IBaseRepository<EwePregnancyCheckRecord> ewePregnancyCheckRecordRepository;
        private readonly IMapper mapper;
        private readonly IBaseRepository<SleepInfor> SleepInforbaseRepository;

        public FemaleRenCreateHandler(IBaseRepository<EwePregnancyCheckRecord> ewePregnancyCheckRecordRepository, IMapper mapper, IBaseRepository<SleepInfor> SleepInforbaseRepository)
        {
            this.ewePregnancyCheckRecordRepository = ewePregnancyCheckRecordRepository;
            this.mapper = mapper;
            this.SleepInforbaseRepository = SleepInforbaseRepository;
        }
        /// <summary>
        /// 种母妊检
        /// </summary>
        /// <param name="request"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        public async Task<Result> Handle(FemaleRenCreateCommand request, CancellationToken cancellationToken)
        {
            var result = new Result() { Code = (int)CodeEnum.add };
            EwePregnancyCheckRecord record = mapper.Map<EwePregnancyCheckRecord>(request);
            //妊检添加成功后，修改妊检状态
            var list = ewePregnancyCheckRecordRepository.Add(record);
            if (list > 0)
            {
                var res=SleepInforbaseRepository.GetAll().FirstOrDefault(x=>x.SleepInforId==request.EarNo);
                if(res != null)
                {
                    res.CheckPre = 1;
                    result.Code=SleepInforbaseRepository.Update(res);
                }
            }
            result.Code = list;
            return result;
        }
    }
}
